package com.ruibang.glass.portal.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.DictInfo;
import com.ruibang.glass.portal.constant.UserErrorCode;
import com.ruibang.glass.portal.domain.DictCondition;
import com.ruibang.glass.portal.entity.DictEntity;
import com.ruibang.glass.portal.mapper.DictMapper;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.model.ResultBody;
import com.teaming.cloud.framework2.common.pojo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: csz
 * @Date: 2018/8/21 09:32
 * @Description:
 */
@Service("dictService")
@Slf4j
public class DictService extends ServiceImpl<DictMapper, DictEntity> implements IService<DictEntity> {


    @Autowired
    private RedisSingleService redisService;


    /**
     * 保存
     *
     * @param entity
     * @return
     */
    public ResultBody<Void> saveDict(DictEntity entity) {
        try {
            if (null == entity)
                return ResultBody.fail(UserErrorCode.PARAM_IS_EMPTY.getCode(), UserErrorCode.PARAM_IS_EMPTY.getMsg());

            DictEntity temp = baseMapper.getDictByCode(entity.getCode());
            if (temp != null && StringUtils.isNotEmpty(temp.getCode())) {
                return ResultBody.fail(UserErrorCode.DICT_IS_EXIST.getCode(), UserErrorCode.DICT_IS_EXIST.getMsg());
            }

            this.save(entity);
            return ResultBody.success();
        } catch (Exception e) {
            log.error("保存字典失败:{}", e.getMessage());
            return ResultBody.fail(UserErrorCode.SAVE_DICT_FAIL.getCode(), UserErrorCode.SAVE_DICT_FAIL.getMsg());
        }
    }

    /**
     * 更新字典
     *
     * @param entity
     * @return
     */
    public ResultBody<Void> updateDict(DictEntity entity) {
        if (null == entity || null == entity.getId())
            return ResultBody.fail(UserErrorCode.PARAM_IS_EMPTY.getCode(), UserErrorCode.PARAM_IS_EMPTY.getMsg());
        try {
            this.updateById(entity);
            return ResultBody.success();
        } catch (Exception e) {
            log.error("更新字典失败:{}", e.getMessage());
            return ResultBody.fail(UserErrorCode.UPDATE_DICT_ERROE.getCode(), UserErrorCode.UPDATE_DICT_ERROE.getMsg());
        }
    }

    /**
     * 根据typeName查询字典信息
     *
     * @return
     */
    public List<DictEntity> getDictByTypeName(String typeName) {
        return baseMapper.getDict(typeName);
    }

    /**
     * 通过 groupName 列表 查询字典属性信息
     *
     * @return
     */
    public List<DictEntity> getDictByGroupNames(List<String> groupNames) {
        return baseMapper.getDictByGroupNames(groupNames);
    }

    /**
     * 分页查询字典数据
     *
     * @param condition
     * @return
     */
    public ResultBody<PageResult<List<DictEntity>>> getAllDict(DictCondition condition) {
        if (null == condition)
            return ResultBody.fail(UserErrorCode.PARAM_IS_EMPTY.getCode(), UserErrorCode.PARAM_IS_EMPTY.getMsg());
        try {
            final LambdaQueryWrapper<DictEntity> lambda = new QueryWrapper<DictEntity>().lambda();
            if (StringUtils.isNotBlank(condition.getName())) {
                lambda.like(DictEntity::getName, condition.getName());
            }

            if (StringUtils.isNotBlank(condition.getGroupType())) {
                lambda.like(DictEntity::getGroupType, condition.getGroupType());
            }
            final IPage<DictEntity> page = this.page(new Page<>(condition.getPageNo(), condition.getPageSize()), lambda);
            PageResult<List<DictEntity>> pageResult = new PageResult<>(page);
            return ResultBody.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询字典失败:{}", e.getMessage());
            return ResultBody.fail(UserErrorCode.PAGESELECT_DICT_ERROE.getCode(), UserErrorCode.PAGESELECT_DICT_ERROE.getMsg());
        }
    }

    /***
     * 设置系统版本
     * @param version
     */
    public void setSystemVersion(String version) {
        DictEntity entity = new DictEntity();
        entity.setCode("system_version");
        entity.setGroupType("system_version");
        QueryWrapper<DictEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(entity);
        DictEntity updateEntity = this.getOne(queryWrapper);
        if (updateEntity != null) {
            updateEntity.setValue(version);
            this.updateById(updateEntity);
        } else {
            entity.setDescription("系统版本");
            entity.setName("系统版本");
            entity.setValue(version);
            this.save(entity);
        }
    }


    /**
     * 获取当前系统版本
     *
     * @return
     */
    public String getSystemVersion() {
        DictEntity entity = new DictEntity();
        entity.setCode("system_version");
        entity.setGroupType("system_version");
        QueryWrapper<DictEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(entity);
        entity = this.getOne(queryWrapper);
        if (entity != null) {
            return entity.getValue();
        }

        return "";
    }


    /***
     * 设置APP更新地址
     * @param address
     */
    public void setAppAddress(String address) {
        DictEntity entity = new DictEntity();
        entity.setCode("app_update_address");
        entity.setGroupType("app_update_address");
        QueryWrapper<DictEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(entity);
        DictEntity updateEntity = this.getOne(queryWrapper);
        if (updateEntity != null) {
            updateEntity.setDescription(address);
            this.updateById(updateEntity);
        } else {
            entity.setDescription(address);
            entity.setName("APP更新地址");
            this.save(entity);
        }
    }


    /**
     * 获取APP更新地址
     *
     * @return
     */
    public String getAppAddress() {
        DictEntity entity = new DictEntity();
        entity.setCode("app_update_address");
        entity.setGroupType("app_update_address");
        QueryWrapper<DictEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(entity);
        entity = this.getOne(queryWrapper);
        if (entity != null) {
            return entity.getDescription();
        }

        return "";
    }


    /**
     * @Description: 获取字典列表
     * @version v1.0
     * @author songJinKang
     * @date 2023-11-27 14:33
     */
    public List<DictEntity> getDictList() {
        return lambdaQuery().list();
    }

    /**
     * 根据字典代码获取字典值
     * @param code
     * @return
     */
    public String getValueByCode(String code){
        return baseMapper.getValueByCode(code);
    }

    /**
     * 根据字典代码跟新字典值
     * @param dict
     */
    public void updateValueByCode(DictInfo dict){
        baseMapper.updateValueByCode(dict);
    }

    public void deleteDict(Long id) {
        this.removeById(id);
        //删除缓存
        redisService.hdel(RedisKey.DICT_GROUP_TYPE,id);
    }
}
